package com.rzico.sbl.ui.order

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOrderWarnBinding
import com.rzico.sbl.model.*
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.OrderViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.phoneReplaceWithStar
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setEmptyImage
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.common_ui.view.BadgeTextView
import com.xinnuo.slimadapter.SlimAdapter
import kotlin.math.abs

class OrderWarnActivity : BaseActivity(R.layout.activity_order_warn) {

    private val mBinding by lazy { ActivityOrderWarnBinding.bind(getRootView()) }

    // 员工列表
    private val mMemberList = arrayListOf(
        FilterData(name = "全部", isChecked = true)
    )

    private var mState = ""
    private var mAdminId = ""

    override fun getViewModel() = get<OrderViewModel>()

    override fun initData() {
        initTitle(title = "超时订单", name = "员工筛选")

        initTabLayout()
        initLayout()
    }

    private fun initTabLayout() {
        mBinding
            .orderTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mState = when (it.position) {
                                0 -> "hope"
                                1 -> "over"
                                else -> ""
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "预超时"
                    },
                    true
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已超时"
                    },
                    false
                )
            }
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyImg.setEmptyImage(
                        resId = R.mipmap.icon_order_no,
                        dpSize = 100f
                    )
                    it.emptyHint.text = "暂无相关订单信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = {
                            getViewModel().warnCount(mAdminId)
                            getData(0)
                        },
                        onLoad = {
                            if (!isLoadingMore) {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                        }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<OrderHeader>(R.layout.item_order_list_title) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_time, bean.hint + bean.time)
                                text(R.id.item_order_status, bean.status_hint)

                                clicked {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn
                                    )
                                }
                            }
                        }
                        .register<OrderGoods>(R.layout.item_order_list_content) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_name, bean.name)
                                text(R.id.item_order_type, "规格：${bean.spec.orEmpty()}")
                                text(R.id.item_order_price, "单价：${bean.price.formatDecimal()}元")
                                text(R.id.item_order_num, "x${bean.quantity}")

                                visibility(
                                    R.id.item_order_img_label,
                                    visibleValue { bean.first }
                                )

                                with<ImageView>(R.id.item_order_img) {
                                    it.loadImage(bean.thumbnail)
                                }

                                with<ImageView>(R.id.item_order_img_type) {
                                    when (bean.methodDescr) {
                                        "offline" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order03)
                                        }

                                        "eleme", "elemengc" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order04)
                                        }

                                        "meituan" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order05)
                                        }

                                        "nongfu" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order06)
                                        }

                                        "jd" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order10)
                                        }

                                        "taobao" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order11)
                                        }

                                        "pinduoduo" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order12)
                                        }

                                        "dummy" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order22)
                                        }

                                        "ali" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order26)
                                        }

                                        else -> it.gone()
                                    }
                                }

                                with<ImageView>(R.id.item_order_img_status) {
                                    it.isVisible = bean.hopeDate.isNotEmpty()

                                    bean.hopeDate.notEmpty {
                                        it.setImageResource(
                                            if (bean.fast) R.mipmap.icon_order07
                                            else R.mipmap.icon_order02
                                        )
                                    }
                                }

                                clicked {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn
                                    )
                                }
                            }
                        }
                        .register<OrderFooter>(R.layout.item_order_list_foot) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_count, bean.total_num)
                                text(R.id.item_order_total, bean.amount.formatDecimal())
                                text(R.id.item_order_total_hint, bean.amountHint)
                                text(R.id.item_order_name, bean.name)
                                text(
                                    R.id.item_order_phone,
                                    when {
                                        userRole in "1,2"
                                                || privacyStatus == "off" -> bean.phone

                                        else -> bean.phone.phoneReplaceWithStar()
                                    }
                                )
                                text(R.id.item_order_addr, bean.address)
                                text(R.id.item_order_done, bean.deliveryDate)
                                text(R.id.item_order_cmemo, bean.cardMemo)
                                text(R.id.item_order_bmemo, bean.memo)

                                getView<View>(R.id.item_order_yu_ll).isVisible =
                                    bean.deliveryDate.isEmpty() && bean.estimateDate.isNotEmpty()
                                getView<View>(R.id.item_order_done_ll)
                                    .isGone = bean.deliveryDate.isEmpty()
                                getView<View>(R.id.item_order_cmemo_ll)
                                    .isGone = bean.cardMemo.isEmpty()
                                getView<View>(R.id.item_order_bmemo_ll)
                                    .isGone = bean.memo.isEmpty()

                                with<TextView>(R.id.item_order_yu) {
                                    val diffTime = getDiffTime(bean.estimateDate)

                                    it.setTextColor(
                                        getColorEx(
                                            if (diffTime > 0) R.color.red
                                            else R.color.orange
                                        )
                                    )

                                    if (diffTime > 0) {
                                        it.text = "${bean.estimateDate.getTimeString()}\n已超时${
                                            formatTime(diffTime)
                                        }"
                                    } else {
                                        it.text = "${bean.estimateDate.getTimeString()}\n${
                                            formatTime(abs(diffTime))
                                        }后超时"
                                    }
                                }

                                with<TextView>(R.id.item_order_pei) { tv ->
                                    tv.text =
                                        "配送员：${bean.adminName}${bean.adminPhone.ifNotEmpty { " - $it" }}"
                                    tv.isGone = bean.adminName.isEmpty()
                                }

                                with<TextView>(R.id.item_order_btn1) {
                                    it.text = bean.hint_btn1
                                    it.isGone = bean.hint_btn1.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unpaid" ->
                                                startActivityEx<OrderConfirmActivity>(
                                                    "amount" to bean.amount.formatDecimal(),
                                                    "orderSn" to bean.orderSN,
                                                    "time" to bean.createDate
                                                )

                                            "unshipped" ->
                                                startActivityEx<OrderShipActivity>("orderSn" to bean.orderSN)

                                            "shipped" ->
                                                if (bean.isShipping) {
                                                    startActivityEx<OrderCancelActivity>(
                                                        "orderSn" to bean.orderSN,
                                                        "shippingSn" to bean.shippingSn
                                                    )
                                                } else refuseOrder(bean.orderSN, bean.position)

                                            "refunding", "returning" ->
                                                refundConfirm(bean.orderSN, bean.position)
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_order_btn2) {
                                    it.text = bean.hint_btn2
                                    it.isGone = bean.hint_btn2.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unpaid" -> updatePrice(
                                                bean.orderSN,
                                                bean.amount,
                                                bean.position
                                            )

                                            "unshipped" -> refundOrder(bean.orderSN, bean.position)
                                            "shipped" ->
                                                startActivityEx<DeliverSendActivity>(
                                                    "mode" to "shipped",
                                                    "orderSn" to bean.orderSN,
                                                    "shippingSn" to bean.shippingSn
                                                )

                                            "refunding", "returning" ->
                                                revokeOrder(bean.orderSN, bean.position)
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_order_btn3) {
                                    it.text = bean.hint_btn3
                                    it.isGone = bean.hint_btn3.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unpaid" -> cancelOrder(bean.orderSN, bean.position)
                                            "unshipped" -> throwOrder(bean.orderSN, bean.position)
                                        }
                                    }
                                }

                                clicked {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn
                                    )
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }

        tvRight?.oneClick {
            if (mMemberList.size > 1) showActionFilter()
            else getViewModel().memberList()
        }
    }

    override fun initListener() {
        // 观察员工筛选数据
        getViewModel()
            .mMemberEvent
            .observe(this) { list ->
                list.mapTo(mMemberList) {
                    FilterData(
                        name = "${it.name}  ${it.mobile}",
                        id = it.id
                    )
                }

                mMemberList.add(
                    FilterData(name = "未指派订单", id = "-1")
                )

                showActionFilter()
            }

        // 观察预超时数量
        getViewModel()
            .mCountOneEvent
            .observe(this) {
                mBinding
                    .orderTab
                    .getTabAt(0)
                    ?.let { tab ->
                        tab.customView
                            ?.find<BadgeTextView>(R.id.item_tab_num)
                            ?.setBadgeCount(it)
                    }
            }

        // 观察已超时数量
        getViewModel()
            .mCountTwoEvent
            .observe(this) {
                mBinding
                    .orderTab
                    .getTabAt(1)
                    ?.let { tab ->
                        tab.customView
                            ?.find<BadgeTextView>(R.id.item_tab_num)
                            ?.setBadgeCount(it)
                    }
            }

        // 观察订单按钮操作
        observe<String>("orderDetail") {
            getViewModel()
                .delay { updateList() }
        }
    }

    /**
     * 员工筛选下拉框
     */
    private fun showActionFilter() {
        getViewModel()
            .showDropFilter(
                context = getIContext(),
                bottom = tvRight!!,
                list = mMemberList
            ) {
                mAdminId = it.id
                updateList()
            }
    }

    /**
     * 订单改价
     */
    private fun updatePrice(orderSN: String, amount: String, index: Int) {
        showPriceDialog(
            title = "订单改价",
            default = amount,
            onSure = { value ->
                getViewModel()
                    .updateOrder(orderSN, value)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("订单改价成功！")

                            val item = mList.find {
                                it is OrderFooter
                                        && it.position == index
                            } as OrderFooter

                            item.amount = value

                            mAdapter.notifyDataSetChanged()

                            // 更新订单列表
                            LiveEventBus
                                .get("orderWarn")
                                .post("refresh")
                        }
                    )
            }
        )
    }

    /**
     * 取消订单
     */
    private fun cancelOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "取消订单",
            hint = "确定要取消订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderCancel, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("取消订单成功！")

                            mList.removeAll {
                                (it is OrderHeader && it.position == index)
                                        || (it is OrderGoods && it.position == index)
                                        || (it is OrderFooter && it.position == index)
                            }

                            mAdapter.notifyDataSetChanged()

                            mBinding
                                .listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()

                            // 更新订单列表
                            LiveEventBus
                                .get("orderWarn")
                                .post("refresh")
                        }
                    )
            }
        )
    }

    /**
     * 抛单
     */
    private fun throwOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "抛单",
            hint = "确定要抛出订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderThrow, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("抛单成功！")

                            operateDone("shipped", index)
                        }
                    )
            }
        )
    }

    /**
     * 申请退款
     */
    private fun refundOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "确认退款",
            hint = "确定要退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderRefund, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("退款成功！")

                            operateDone("returned", index)
                        }
                    )
            }
        )
    }

    /**
     * 申请退货退款
     */
    private fun refuseOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "退货退款",
            hint = "确定要退货退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderReturn, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("退货退款成功！")

                            operateDone("returned", index)
                        }
                    )
            }
        )
    }

    /**
     * 确认退款
     */
    private fun refundConfirm(orderSN: String, index: Int) {
        showHintDialog(
            title = "确认退款",
            hint = "确定要同意退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderRefund, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("确认退款成功！")

                            operateDone("returned", index)
                        }
                    )
            }
        )
    }

    /**
     * 撤销退款
     */
    private fun revokeOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "撤销退款",
            hint = "确定要撤销退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderBack, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("撤销退款成功！")

                            operateDone("unshipped", index)
                        }
                    )
            }
        )
    }

    /**
     * 点击按钮完成后的操作
     */
    private fun operateDone(
        flag: String,
        index: Int,
        extra: String = ""
    ) {
        val itemHeader = mList.find {
            it is OrderHeader && it.position == index
        } as OrderHeader

        val itemFooter = mList.find {
            it is OrderFooter && it.position == index
        } as OrderFooter

        when (flag) {
            "unshipped" -> {
                itemHeader.status_hint = "待发货"
                itemFooter.status = flag
                itemFooter.hint_btn1 = "发货"
                itemFooter.hint_btn2 = if (userRole == "1") "退款" else ""
                itemFooter.hint_btn3 = if (itemFooter.allowRob) "抛单" else ""
            }

            "shipped" -> {
                itemHeader.status_hint = "已发货"
                itemFooter.status = flag
                itemFooter.adminName = extra
                itemFooter.hint_btn1 = if (userRole == "1") "退货退款" else ""
                itemFooter.hint_btn2 = "转派"
                itemFooter.hint_btn3 = ""
            }

            "returned" -> {
                itemHeader.status_hint = "已退款"
                itemFooter.status = flag
                itemFooter.hint_btn1 = ""
                itemFooter.hint_btn2 = ""
                itemFooter.hint_btn3 = ""
            }

            "review" -> {
                itemHeader.status_hint = "待评价"
                itemFooter.status = flag
                itemFooter.hint_btn1 = ""
                itemFooter.hint_btn2 = ""
                itemFooter.hint_btn3 = ""
            }
        }

        mAdapter.notifyDataSetChanged()

        // 更新订单列表
        LiveEventBus
            .get("orderWarn")
            .post("refresh")
    }

    /**
     * 获取列表数据
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderWarnList(
                page = index,
                state = mState,
                roleId = userRole,
                adminId = mAdminId,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getViewModel().warnCount(mAdminId)
        getData(0)
    }

}